package com.bridgeintelligent.tag.bulkload.api.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description
 * @author: grp 2021-03-06 14:30
 **/
public class ZipUtils {

    public static void zipMore(String zipFileName, File... inputFile) throws IOException {
        try(FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
                    new CRC32());
            ZipOutputStream out = new ZipOutputStream(cos)){
            zip(out, inputFile);
        }
    }

    private static void zip(ZipOutputStream out, File... sources) throws IOException {
        for(File source:sources){
            zipOne(out, source);
        }
        out.flush();
    }

    private static void zipOne(ZipOutputStream out, File source) throws IOException {
        ZipEntry zipEntry = new ZipEntry(getFileName(source.getName()));
        out.putNextEntry(zipEntry);
        FileInputStream in = new FileInputStream(source);
        int block;
        while ((block = in.read()) != -1) {
            out.write(block);
        }
        in.close();
    }

    private static String getFileName(String name){
        return name.substring(name.lastIndexOf("_")+1);
    }
}
